package com.example.shiro;

import com.example.biz.IUserBiz;
import com.example.pojo.User;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @Author:帅帅的刘
 * @Description:
 * @Date:Create In 2019-09-16 16:01
 **/
public class AuthRealm extends AuthorizingRealm {

    @Autowired
    private IUserBiz userBiz;

    // 授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    // 认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //token携带了用户信息
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
        //获取前端输入的用户名
        String userName = usernamePasswordToken.getUsername();
        //根据用户名查询数据库中对应的记录
        User user = userBiz.findUser(userName);
        if (user == null) {
            throw new UnknownAccountException("账户不存在");
        }
        if (user.getState() == 1) {
            throw new LockedAccountException("账户被禁用");
        }
        //当前realm对象的name  返回一个字符串
        String realmName = getName();

        //盐值
        ByteSource credentialsSalt = ByteSource.Util.bytes(user.getUserName());

        //封装用户信息，构建AuthenticationInfo对象并返回
        AuthenticationInfo authcInfo = new SimpleAuthenticationInfo(user, user.getPassWord(),
                credentialsSalt,   realmName);
        return authcInfo;
    }

}


